import datetime

from django.db import models

from social.account.models import User
from social.exceptions import InsufficientBalanceException
from social.utils.models import BaseModel


class AVCall(BaseModel):
    WAITING = 0
    ING = 1
    OVER = 2
    ABNORMAL_OVER = 3  # 非正常结束，网络异常或者余额不足
    REJECT = 4  # 取消
    CANCEL = 5  # 拒绝

    from_user = models.ForeignKey(User, related_name='av_call_from', on_delete=models.CASCADE)
    to_user = models.ForeignKey(User, related_name='av_call_to', on_delete=models.CASCADE)
    who_pay = models.CharField(null=True, max_length=20)
    coin = models.IntegerField(default=0)
    total_coin = models.IntegerField(default=0)
    type = models.CharField(max_length=10)
    status = models.IntegerField(default=0)
    ranked = models.BooleanField(default=False)
    compute_time = models.BooleanField(default=False)
    call_id = models.CharField(max_length=100, null=True, unique=True)
    # 开始时间
    create_time = models.IntegerField(default=0)
    # 结束时间
    destroy_time = models.IntegerField(default=0)

    def is_running(self):
        from_tick, _ = AVChatTickTime.objects.get_or_create(chat_id=self.id, user_id=self.from_user_id)
        to_tick, _ = AVChatTickTime.objects.get_or_create(chat_id=self.id, user_id=self.to_user_id)
        from_tick_time = from_tick.updated_at.timestamp()
        to_tick_time = to_tick.updated_at.timestamp()
        now = datetime.datetime.now().timestamp()
        if now - from_tick_time > 15 or now - to_tick_time > 15:
            # 有一端超过30s没有响应
            self.status = AVCall.ABNORMAL_OVER
            self.destroy_time = min(from_tick_time, to_tick_time)
            self.save(update_fields=['status', 'destroy_time'])
            return False
        return True

    @property
    def duration(self):
        if self.status in [AVCall.OVER, AVCall.ABNORMAL_OVER]:
            return self.destroy_time - self.create_time
        else:
            return 0

    def update_wallet_record(self, coin, total_min, total_coin):
        from social.payment.models import Wallet
        from social.payment.models import WalletRecord
        try:
            self.refresh_from_db()
            if self.total_coin == total_coin:
                return
            self.total_coin = total_coin
            self.save(update_fields=['total_coin'])
            if self.who_pay == 'from':
                # from 消费
                wallet1, _ = Wallet.objects.get_or_create(user=self.from_user)
                consume = wallet1.consume(coin)
                WalletRecord.set_av_call_record(self.from_user,
                                                f'和{self.to_user.nickname}视频聊天{total_min}分钟（增加{total_coin}点财富值）',
                                                -consume, WalletRecord.COIN, self.id)
                # to 收入
                wallet2, _ = Wallet.objects.get_or_create(user=self.to_user)
                income = wallet2.earning(coin)
                WalletRecord.set_av_call_record(self.to_user,
                                                f'和{self.from_user.nickname}视频聊天{total_min}分钟',
                                                income, WalletRecord.INCOME, self.id)
            else:
                # to 消费
                wallet1, _ = Wallet.objects.get_or_create(user=self.to_user)
                consume = wallet1.consume(coin)
                WalletRecord.set_av_call_record(self.to_user,
                                                f'和{self.from_user.nickname}视频聊天{total_min}分钟（增加{total_coin}点财富值）',
                                                -consume, WalletRecord.COIN, self.id)

                # from 收入
                wallet2, _ = Wallet.objects.get_or_create(user=self.from_user)
                income = wallet2.earning(coin)
                WalletRecord.set_av_call_record(self.to_user,
                                                f'和{self.to_user.nickname}视频聊天{total_min}分钟',
                                                income, WalletRecord.INCOME, self.id)

        except InsufficientBalanceException:
            self.status = AVCall.ABNORMAL_OVER
            self.destroy_time = datetime.datetime.now().timestamp()
            self.save(update_fields=['status', 'destroy_time'])


class AVChatTickTime(BaseModel):
    chat_id = models.IntegerField()
    user_id = models.IntegerField()

    class Meta:
        unique_together = (('chat_id', 'user_id'),)
